<template>
  <div class="apply-read-dialog">
    <MyDialog
      :show="isApplyRead"
      customName="apply-read-dialog"
      dialogWidth="850px"
      @beforeClose="beforeClose"
    >
      <template #body>
        <el-form
          :rules="rulesForm"
          :model="applyForm"
          label-width="110px"
          size="small"
          ref="applyReadForm"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item prop="subType" label="调阅方式：">
                <el-select
                  v-model="applyForm.subType"
                  placeholder="请选择调阅方式"
                  @change="changeSubType"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in applySubType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col
              :span="12"
              v-if="applyForm.subType == 1 || applyForm.subType == 6"
            >
              <el-form-item prop="borrowSign" label="调阅标识：">
                <el-radio-group
                  v-model="applyForm.borrowSign"
                  @change="borrowSignChange"
                >
                  <el-radio :label="0">窍楚配送</el-radio>
                  <el-radio :label="1" v-if="applyForm.subType == 1"
                    >自提</el-radio
                  >
                  <el-radio :label="2" v-if="applyForm.subType == 1"
                    >来库</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="调阅用途：" prop="borrowPurposes">
                <el-input
                  placeholder="请输入调阅用途"
                  v-model="applyForm.borrowPurposes"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" v-if="isexpand">
              <el-form-item label="调阅明细：">
                <div class="more-box-show">
                  <p>注：窍数量较多时，建议上传附件，可收起更多明细</p>
                  <!-- 循环已选中的窍 -->
                  <div class="selected-list">
                    <div class="select-item">
                      <el-form
                        label-width="125px"
                        size="small"
                        ref="loopDetailForm"
                      >
                        <el-col
                          :span="23"
                          v-for="(item, index) in selectedList"
                          :key="index"
                        >
                          <el-form-item
                            :label="String(item.boxCode)"
                            :rules="[
                              { required: true, message: '明细不能为空' },
                            ]"
                          >
                            <el-input
                              placeholder="请输入明细"
                              v-model="loopForm[item.userBoxId]"
                              clearable
                            ></el-input>
                          </el-form-item>
                        </el-col>
                      </el-form>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" v-if="!isexpand">
              <el-form-item label="调阅明细：" prop="applydetail">
                <el-input
                  placeholder="请输入内容"
                  v-model="applyForm.applydetail"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <div class="show-more">
            <div @click="isexpand = !isexpand" v-if="!isexpand" class="more">
              展开更多明细 <i class="el-icon-arrow-down"></i>
            </div>
            <div @click="isexpand = !isexpand" v-if="isexpand" class="more">
              收起更多明细 <i class="el-icon-arrow-up"></i>
            </div>
          </div>
          <el-row>
            <el-col :span="24">
              <el-form-item label="上传附件：">
                <el-button type="info" size="small" round v-if="isShowRemind" @click="showRemind">选择附件</el-button>
                <el-upload
                  v-else
                  class="upload-demo"
                  action
                  ref="uploadButtonApply"
                  :http-request="modeUpload"
                  :before-upload="beforeUpload"
                  :on-change="handleTopImageSuccess"
                  :file-list="fileList"
                  :on-remove="handleRemove"
                  :limit="5"
                  multiple
                >
                  <el-button type="info" size="small" round>选择附件</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="applyForm.subType == 3">
            <el-col :span="12">
              <el-form-item prop="isEncrypted" label="是否加密：">
                <el-select
                  v-model="applyForm.isEncrypted"
                  placeholder="请选择是否加密"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in encryption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="isUrgent" label="是否加急">
                <el-select
                  v-model="applyForm.isUrgent"
                  @change="isUrgentChange"
                  placeholder="请选择是否加急"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in encryption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item prop="borrowClarity" label="清晰度：">
                <el-select
                  v-model="applyForm.borrowClarity"
                  placeholder="请选择清晰度"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in clarityType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item> -->
            </el-col>
          </el-row>
          <el-row v-if="applyForm.subType == 3 || applyForm.borrowSign != 0">
            <el-col :span="12" v-if="isService">
              <el-form-item prop="contactName" label="联系人：">
                <el-select
                  style="width: 100%"
                  v-model="applyForm.contactName"
                  filterable
                  remote
                  :remote-method="remoteMethod"
                  allow-create
                  placeholder="请输入联系人"
                  @change="contactChange"
                  clearable
                  :loading="loading">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    <span style="">{{ item.label }}</span>
                    <span style="" v-if="item.contactMobile">{{ '-' + item.contactMobile + '-' + item.contactEmail }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-else>
              <el-form-item prop="contactName" label="联系人：">
                <el-input
                  placeholder="请输入联系人"
                  v-model="applyForm.contactName"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="contactMobile" label="联系方式：">
                <el-input
                  placeholder="请输入联系方式"
                  v-model="applyForm.contactMobile"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item prop="files" label="申请人：">
                <span>{{ userInfo.realName }}({{ userInfo.mobile }})</span>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="applyForm.subType == 6">
              <el-form-item prop="reviewerUserId" label="审核人：">
                <el-select
                  v-model="applyForm.reviewerUserId"
                  placeholder="请输入审核人姓名进行检索"
                  style="width: 100%"
                  filterable
                  remote
                  :remote-method="getUserListddd"
                >
                  <el-option
                    v-for="item in userList"
                    :key="item.id"
                    :label="(item.fullName + '-' + item.mobile)"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="applyForm.subType == 3">
              <el-form-item prop="contactEmail" label="邮箱地址：">
                <el-input
                  placeholder="请输入邮箱地址"
                  v-model="applyForm.contactEmail"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="applyForm.subType !== 3 && applyForm.borrowSign == 0">
            <el-col :span="20" class="address-list">
              <el-form-item prop="addressIndex" label="选择地址：">
                <el-radio-group v-model="applyForm.addressIndex" @change="addressRadioChange">
                  <div class="address-item" v-for="(item, index) in addressList"
                  :key="index">
                  <el-radio
                    :label="index"
                  >
                    <span @dblclick.prevent="getAdd(item)">
                      <span>
                        {{ item.fullArea }}{{ item.address }}
                      </span>
                      <span>
                        {{ item.mobile }}
                      </span>
                      <span>
                        {{ item.fullName }}
                      </span>
                    </span>
                  </el-radio>
                </div>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="4">
              <div class="add-address-btu">
                <el-button type="text" @click="showAddAddress" size="mini">
                  <i class="el-icon-plus"></i>
                  添加地址</el-button
                >
              </div>
            </el-col>
          </el-row>

          <el-row v-if="applyForm.borrowSign != null && applyForm.borrowSign != 0">
            <el-col :span="23">
              <el-form-item label="提窍地址:">
                <span slot="label" class="delivery-label">
                  <span>提窍地址</span>
                  <el-popover placement="top" width="250" trigger="hover">
                    <div class="on-time">
                      <p>网点自提服务</p>
                      <div>
                        网点自提服务暂时不额外收取费用，但为确保您的权益，请您在收到服务站审核通知的短信后，及时凭手机验证码进行操作。
                      </div>
                    </div>

                    <div slot="reference" class="popover-reference">
                      <el-button type="text">
                        <i class="el-icon-question"></i>
                      </el-button>
                    </div>
                  </el-popover>
                  <span>：</span>
                </span>

                <div
                  v-for="(address, index) in extractBoxAddressList"
                  :key="index"
                >
                  <div class="extract-map">
                    <div>{{ address.address }}</div>
                    <div @click="toShowMap(address)" class="map-show">
                      <i class="el-icon-location-information"></i>地图
                    </div>
                  </div>
                </div>

              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="10" v-if="applyForm.subType !== 3">
              <el-form-item prop="deliveryOn">
                <span slot="label" class="delivery-label">
                  <span>调阅时间</span>
                  <el-popover placement="top" width="250" trigger="hover">
                    <div class="on-time">
                      <p>请至少提前一天预约</p>
                      <div>
                        如无特殊情况，当天原件调阅需要支付额外的加急费用。客服将很快和您确认时间，请保持手机畅通。
                      </div>
                    </div>

                    <div slot="reference" class="popover-reference">
                      <el-button type="text">
                        <i class="el-icon-question"></i>
                      </el-button>
                    </div>
                  </el-popover>
                  <span>：</span>
                </span>

                <el-date-picker
                  @change="changeDatePicker"
                  v-model="applyForm.deliveryOn"
                  type="date"
                  placeholder="选择调阅时间"
                  :clearable="false"
                  :picker-options="forbiddenTime"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="4" v-if="applyForm.subType !== 3">
              <el-popover placement="top" width="250" trigger="hover">
                <div class="on-time">
                  <p>准时服务承诺</p>
                  <div>
                    当您下单选择了窍楚的服务， 我们承诺在您选择的时间内送达
                  </div>
                  <div>
                    若由于窍楚原因未能准时送达， 您可通过’在线客服‘提交申请，
                    经客服审核确认后， 将按照您支付的配送费返利至您的账户
                  </div>
                </div>

                <span slot="reference" class="popover-reference">
                  <el-button type="text">
                    <i class="el-icon-present"></i>准时服务承诺
                  </el-button>
                </span>
              </el-popover>
            </el-col>
            <el-col :span="3" v-if="applyForm.subType !== 3">
              <el-button type="text" @click="toSeeCost">
                <i class="el-icon-search"></i>物流费用标准
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <div slot="title">
        <div class="dialog-title">申请调阅</div>
      </div>
      <div slot="footer">
        <span>
          <el-button size="small" @click="applyClose">取 消</el-button>
          <el-button
            size="small"
            type="primary"
            :loading="btnLoading"
            :disabled="canGo"
            @click="applyConfirm('applyReadForm')"
            >提交</el-button
          >
        </span>
      </div>
    </MyDialog>

    <AddressEdit
      :isShowAddAddress="isShowAddAddress"
      title="添加地址"
      @closeDialog="closeAddressDialog"
    />

    <LogisticsCost
      title="物流上门收费标准"
      :isShowCost="isShowCost"
      @closeDialog="closeCostDialog"
    />

    <MapShowDialog
      :mapAddressShow="mapAddressShow"
      :isShowMap="isShowMap"
      @closeDialog="closeMapDialog"
    />

    <!-- 当天日期加急提示 -->
    <MyDialog
      :show="isTipShow"
      @beforeClose="isTipShow = false"
      title="加急提示"
    >
      <template #body>
        <div class="tip-box">
          <div class="content">
            <!-- 扫描件的加急提示 -->
            <span v-if="applyForm.isUrgent == 1 && applyForm.subType == 3">尊敬的客户您好，您现在选择的是当天加急服务，如需限时加急服务，欢迎致电400-877-0039。</span>
            <span v-else>尊敬的客户您好，您当前选择的是当天加急服务，根据合同约定，
              或需支付额外的加急费用。如需限时加急服务，请致电400-877-0039。</span>
          </div>
        </div>
      </template>
    </MyDialog>

    <UploadRemind :visible="dialogVisible" @close="handleClose" @submit="handleSubmit" :info="info"></UploadRemind>
  </div>
</template>

<script>
import { getRemindInfo } from '@/api/access-manage/index'
import UploadRemind from '@/components/uploadRemind.vue';

import Cookies from "js-cookie";
import { checkPhone, checkEmail } from "../../../utils/common";
import {
  encryption,
  applySubType,
  clarityType,
} from "../../../utils/dictionary.js";
import {
  toApplyBorrow,
  toUploadFile,
  getDepotList,
  getUserList,
  contractPeopleList
} from "@/api/access-manage/index";
import { getAddressList } from "../../../api/member/address";
import AddressEdit from "./AddressEdit";
import LogisticsCost from "./LogisticsCost";
import MapShowDialog from "./MapShowDialog";

export default {
  name: "ApplyReadDialog",
  props: {
    isApplyRead: {
      type: Boolean,
      default: false,
    },
    userInfo: {
      type: Object,
      default: () => {},
    },
    selectedList: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    AddressEdit,
    LogisticsCost,
    MapShowDialog,
    UploadRemind
  },
  watch: {
    isApplyRead() {
      if (this.isApplyRead) {
        if (this.isPrivateLocalF) {
          this.judgeShowRemind()
          this.isShowRemind = true
        }

        // 是否是客服 - 有 id == 8 的角色
        this.isService = JSON.parse(Cookies.get('userInfo'))?.roleList.filter(m => m.id == 8).length > 0
        // JSON.parse(Cookies.get('userInfo'))?.mobile == '18014702925'
        this.getAddressList();
        this.getDepotList();

        this.applyForm.contactName = this.userInfo.realName;
        this.applyForm.contactMobile = this.userInfo.mobile;
        this.applyForm.contactEmail = this.userInfo.email;
        this.isexpand = false;
        // this.filePathList = [];
        this.applyForm.deliveryOn = Date.now() + 8.64e7;
      } else {
        this.applyForm = {
          subType: 3,
          addressIndex: undefined,
          borrowSign: 0, // 调阅标识
          borrowPurposes: "",
          applydetail: "",

          isEncrypted: 0,
          isUrgent: 0,
          // borrowClarity: 0,
          reviewerUserId:null,

          contactName: "",
          contactMobile: "",
          contactEmail: "",
          deliveryOn: undefined
        };
        this.uploadFileList = [];
        this.canGo = false
      }
    },
  },
  data() {
    return {
      info: '上传附件提醒',
      dialogVisible: false, // 上传附件提示框
      isShowRemind: false,

      isPrivateLocal: process.env.VUE_APP_LOCAL == 'huaian',
      isPrivateLocalF: process.env.VUE_APP_LOCAL == 'fangshan',
      isService: false,
      options: [],
      loading: false,
      uploading: false,
      // allowApply: true, // 是否允许申请
      canGo: false, // 自提 提窍地址为 无 时 禁止提交
      forbiddenTime: {
        //禁用当前日期之前的日期
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      mapAddressShow: {},
      isShowMap: false,
      isShowCost: false,
      btnLoading: false,
      fileList: [],
      uploadFileList: [],
      // filePathList: [],
      isShowAddAddress: false,
      addressList: [],
      isexpand: false,
      loopForm: {},
      encryption: encryption,
      applySubType: applySubType,
      clarityType: clarityType,
      applyForm: {
        subType: 3,
        addressIndex: undefined,
        borrowSign: 0, // 调阅标识
        borrowPurposes: "",
        applydetail: "",

        isEncrypted: 0,
        isUrgent: 0,
        // borrowClarity: 0,
        reviewerUserId:null,

        contactName: "",
        contactMobile: "",
        contactEmail: "",

        deliveryOn: Date.now() + 8.64e7,
      },
      rulesForm: {
        subType: [
          { required: true, message: "请选择调阅方式", trigger: "change" },
        ],
        borrowPurposes: [
          { required: true, message: "请输入请调阅用途" },
          {
            min: 1,
            max: 100,
            message: "调阅用途大于1个字符， 小于100个字符",
            trigger: "blur",
          },
        ],
        applydetail: [
          { required: true, message: "请输入调阅明细" },
          {
            min: 1,
            max: 255,
            message: "调阅明细大于1个字符， 小于255个字符",
            trigger: "blur",
          },
        ],

        addressIndex: [{ required: true, message: "请选择地址" }],

        reviewerUserId: [{ required: true, message: "请选择审核人" }],

        contactName: [{ required: true, message: "请输入联系人" }],
        contactMobile: [
          { required: true, message: "请输入联系方式" },
          { validator: checkPhone, trigger: ["blur", "change"] },
        ],
        contactEmail: [
          { required: true, message: "请输入邮箱地址" },
          { validator: checkEmail, trigger: ["blur", "change"] },
        ],
        deliveryOn: {
          required: true,
          message: "请选择调阅时间",
        },
      },
      extractBoxAddressList: [],
      isTipShow: false,
      userList: []
    };
  },

  methods: {
    // 调用接口，判断是否需要展示提示按钮， 有值,将值复制到框里
    judgeShowRemind() {
      // 接口
      getRemindInfo().then(res => {
        console.log(res, '哈哈哈哈哈哈或或或')
        this.info = res.data
        if(res.data == null) {
          this.isShowRemind = false
        }
      })

      // 赋值
    },
    // 展示上传文件提示框
    showRemind() {
      this.dialogVisible = true
    },
    handleSubmit() {
      this.dialogVisible = false
      this.isShowRemind = false
    },
    handleClose() {
      this.dialogVisible = false
    },

    getAdd(item) {
      let content = item.fullArea + item.address + item.mobile + item.fullName

      // 将数据放到粘贴版上
      // 双击复制
      let save = function (e){
        e.clipboardData.setData('text/plain',content); 
        e.preventDefault();  //阻止默认行为
      }
      document.addEventListener('copy',save);//添加一个copy事件
      document.execCommand("copy");//执行copy方法
      this.$message({message: '地址复制成功', type:'success'})//提示
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        contractPeopleList({contactName: query}).then(res => {
          this.options = []
          res.data.map(m => {
            this.options.push({
              label: m.contactName,
              //  + '-' + m.contactMobile + '-' + m.contactEmail,
              value: m.contactName + '-' + m.contactMobile + '-' + m.contactEmail,
              contactMobile: m.contactMobile,
              contactEmail: m.contactEmail
            })
          })
          this.loading = false
        })
      } else {
        this.options = [];
      }
    },
    // 是否加急改变
    isUrgentChange(value) {
      // 选择是， 展示提示；否 不提示
      if (value == 1) {
        this.isTipShow = true
      } else {
        this.isTipShow = false
      }
    },
    // 联系人变化后 更改 手机及邮箱
    contactChange(value) {
      let selected = this.options.filter(m => m.value == value)[0]
      if (selected) {
        this.applyForm.contactMobile = selected.contactMobile
        this.applyForm.contactEmail = selected.contactEmail
        this.applyForm.contactName = selected.label
      }
    },
    // 调阅时间改变
    changeDatePicker(value) {
      if (
        new Date(value).toLocaleDateString() === new Date().toLocaleDateString()
      ) {
        // 当天日期 跳出提示弹窗
        this.isTipShow = true;
      }
    },
    // 获得提窍地址
    getDepotList() {
      this.extractBoxAddressList = [];

      this.selectedList.map((e) => {
        getDepotList({ id: e.depotId }).then((res) => {
          if (
            this.extractBoxAddressList.filter((m) => m.id === e.depotId)
              .length == 0
          ) {
            this.extractBoxAddressList.push(res.data[0]);
          }
        });
      });
    },
    getUserListddd(key) {
      this.getUserList(1, null, key)
    },
    // 获得审核人列表
    getUserList(type, mobile, realName) {
      // type 2 - 有mobile 判断当前地址中的人是否 是 用户
      // 获得当前登录人的companyId
       const companyId = JSON.parse(localStorage.getItem("localUserInfo")).company.id
        const data = {
          status: 1, // 启用
          companyId: companyId,
          mobile: mobile && mobile,
          realName: realName
        }
        getUserList(data).then((res) => {
          if (type == 2 && res.code == 200) {
            if (res.data.length == 0) {
              // 不是当前公司用户，重新选择审核人
              this.applyForm.reviewerUserId = null
            } else {
              // 不是当前公司用户，以他为审核人
              this.applyForm.reviewerUserId = res.data[0].id
            }
          }
          // else 
          if (res.code == 200) {
            // 得到用户列表
            this.userList= res.data
          }
        });
    },
    // 地址选择变化
    addressRadioChange(val) {
      const mobile = this.addressList[val].mobile
      this.getUserList(2, mobile)
    },
    // 新增地址弹窗
    closeAddressDialog() {
      this.isShowAddAddress = false;
      this.getAddressList();
    },
    // 查看地图定位
    toShowMap(address) {
      this.mapAddressShow = address;
      this.isShowMap = true;
    },
    //关闭地图定位弹窗
    closeMapDialog() {
      this.isShowMap = false;
    },
    // 查看物流费
    toSeeCost() {
      this.isShowCost = true;
    },
    //关闭物流费弹窗
    closeCostDialog() {
      this.isShowCost = false;
    },
    // 文件上传
    modeUpload(param) {
      this.uploadFileList.push(param);
      this.toUploadFile(param);
    },
    // 文件移除
    handleRemove(file, fileList) {
      // 从this.uploadFileList移除
      let list = [];
      this.uploadFileList.map((e) => {
        if (e.file.uid != file.uid) {
          list.push(e);
        }
      });
      this.uploadFileList = list;

      // let pathList = [];
      // this.filePathList.map((m) => {
      //   if (m.uid != file.uid) {
      //     pathList.push(m);
      //   }
      // });
      // this.filePathList = pathList;

      // this.toUploadFile();
    },
    // 上传文件限制
    beforeUpload(file) {
      // 限制文件最大为10MB
      const isLt10M = file.size / 1024 / 1024 <= 10;
      if(!isLt10M) {this.$message.warning('上传文件大小不能超过 10MB!');}

      // this.uploadFileList 中 已有此文件 则 返回 false
      let isRepeat = this.uploadFileList.filter(e => e.file.name == file.name).length > 0
      if (isRepeat) {this.$message.warning('上传文件重复');}

      return isLt10M && !isRepeat;
    },
    // 上传成功后
    handleTopImageSuccess() {
      // this.$refs.uploadButton.submit();
      // // 确定上传后需 清空文件 否则会多次上传
      // this.$refs.uploadButton.clearFiles();
    },
    // 展开添加地址弹窗
    showAddAddress() {
      this.isShowAddAddress = true;
    },
    // 获得地址列表
    getAddressList() {
      getAddressList().then((res) => {
        this.addressList = res.data;
        
       this.applyForm.addressIndex = res.data.findIndex(e => e.isDefault == 1)
      });
    },
    // 调阅方式改变
    changeSubType(val) {
      this.$refs["applyReadForm"].clearValidate();
      this.borrowSignChange() // 调阅标识改变
      if (val == 6) {
        this.applyForm.borrowSign = 0;
        // this.getUserList(1)
      }
      if (val != 3) {
        this.applyForm.deliveryOn = Date.now() + 8.64e7,
        this.getAddressList();
        // 邮箱置空
        this.applyForm.contactEmail = null
      }

      if (val == 1) {
        // 调阅明细不必填
        this.rulesForm.applydetail[0].required = false
      } else {
        this.rulesForm.applydetail[0].required = true
      }
      this.$forceUpdate();
    },
    // 调阅方式改变
    borrowSignChange() {
      this.$refs["applyReadForm"].clearValidate();
      // 如果 自提或来库
      if (this.applyForm.borrowSign == 1 || this.applyForm.borrowSign == 2) {
        if (this.extractBoxAddressList.filter(e => e.address == '无').length >0) {
          this.canGo = true
          this.$message({
            type:'warning',
            message: '窍未绑定仓库，请重新选择窍'

          })
        }
      }
    },
    // 关闭调阅窗口
    beforeClose() {
      this.$emit("closeApplyDialog");
    },
    // 取消按钮 - 关闭表单
    applyClose() {
      this.$emit("closeApplyDialog");
    },
    //  上传文件附件
    toUploadFile(param) {
      this.uploading = true
      let formData = new FormData();
      // this.uploadFileList.map((e) => {
      //   formData.append("file", e.file);
      // });
      formData.append("file", param.file);
      // if (this.uploadFileList.length == 0) {
      //   this.filePathList= []
      //   return 
      // }
      // { id: 0 }
      toUploadFile(formData)
        .then((res) => {
          if (res.code == 200) {
            this.uploading = false
            // this.filePathList = res.data;
            // this.filePathList.push({path: res.data[0], uid: param.file.uid, name: param.file.uid})

            this.uploadFileList.filter(m => m.file.uid == param.file.uid)[0]['path'] = res.data[0]
          } else {
            this.uploading = false
          }
        })
        .catch((err) => {
          this.uploading = false;
        });
    },
    //申请调阅 表单提交
    applyConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (
            this.isexpand &&
            Object.keys(this.loopForm).length != this.selectedList.length
          ) {
            this.$message.info("请填写全部明细");
            return;
          }

          console.log(this.uploadFileList, this.uploadFileList.filter(c => !c.path), '哈哈哈哈哈哈哈哈哈')
          // if (this.uploading || (!this.uploading && this.filePathList.length !== this.uploadFileList.length)) {
          if (this.uploadFileList.filter(c => !c.path).length > 0) {
            this.$message.info("请等待附件上传完成后提交");
            return
          }
          this.btnLoading = true;
          // let userBoxIdList = [];
          // this.selectedList.map((e) => {
          //   userBoxIdList.push(e.id);
          // });

          // let userBoxDesc = {};
          // if (!this.isexpand) {
          //   this.selectedList.map((e) => {
          //     userBoxDesc[e.id] = this.applyForm.applydetail;
          //   });
          // } else if (this.isexpand) {
          //   userBoxDesc = { ...this.loopForm };
          // }

          let userBoxList = [];
          // this.selectedList.map((e) => {
          //   userBoxList.push({id: e.id, boxCode: e.boxCode});
          // });

          // let userBoxDesc = {};
          if (!this.isexpand) {
            // this.selectedList.map((e) => {
            //   userBoxDesc[e.id] = this.applyForm.applydetail;
            // });

            this.selectedList.map((e) => {
              userBoxList.push({
                userBoxId: e.userBoxId,
                boxCode: e.boxCode,
                detail: this.applyForm.applydetail,
                userId: e.userId
              });
            });
          } else if (this.isexpand) {
            // userBoxDesc = { ...this.loopForm };

            this.selectedList.map((e) => {
              userBoxList.push({
                userBoxId: e.userBoxId,
                boxCode: e.boxCode,
                detail: this.loopForm[e.userBoxId],
              });
            });
          }

          let addressInfo = {};

          if (this.applyForm.subType !== 3) {
            addressInfo.deliveryOn =
              this.$moment(this.applyForm.deliveryOn).valueOf() / 1000;

            if (this.applyForm.borrowSign == 0) {
              if (this.applyForm.addressIndex === -1) {
                this.$message.error('请选择或新增默认地址')
                this.btnLoading = false
                return
              }
              // 有地址
              let selected = this.addressList[this.applyForm.addressIndex]

              addressInfo.address = selected.fullArea + selected.address;

              addressInfo.contactName = selected.fullName;
              addressInfo.contactMobile = selected.mobile;
            }
          } else if (this.applyForm.subType == 3) {
            this.applyForm.borrowSign = null
            this.applyForm.deliveryOn = null
          }

          // if (this.uploadFileList.length !== this.filePathList.length) {
          //   this.$message.error('请等待文件上传完成后再提交')
          // }

          // 获得路径url
          const urlArr = []
          this.uploadFileList.map(m => {
            urlArr.push(m.path)
          })

          const data = {
            // type: 0, // 调阅
            ...this.applyForm,

            // userBoxDesc: userBoxDesc,
            userBoxList: userBoxList,

            ...addressInfo,
            filePathList: urlArr
            // this.filePathList,
          };

          new Promise((resolve) => {
            toApplyBorrow(data)
              .then((res) => {
                this.btnLoading = false;
                this.$message({
                  type: "success",
                  message: "申请成功",
                });
                this.$emit("closeApplyDialog");
                this.$emit("getList");

                // 跳转至调阅列表
                this.$router.push({ path: "/retrieval/log" });
              })
              .catch((err) => {
                this.btnLoading = false;
                this.$emit("closeApplyDialog");
              });
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.apply-read-dialog {
  .dialog-title {
    color: #f88123;
    font-size: 16px;
  }
  .more-box-show {
    background: #eee;
    color: #f88123;
    padding-left: 10px;

    .selected-list {
      max-height: 200px;
      overflow-y: scroll;
    }
  }
  .show-more {
    color: #f88123;
    padding-left: 18px;
    margin-bottom: 10px;
    line-height: 30px;
    .more {
      width: 120px;
      cursor: pointer;
    }
  }
}

.address-list {
  ::v-deep  .el-radio-group {
    display: flex;
    flex-direction: column;
    padding-top: 4px;
    min-height: 30px;
    overflow-y: scroll;
    // 不展示滚动条
    &::-webkit-scrollbar {
      display: none;
    }
    .el-radio {
      display: flex;
      align-items: center;
      margin: 5px 0;
      .address-item {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        line-height: 18px;
        span {
          margin-right: 10px;
        }
      }
    }
  }
}
.add-address-btu {
  padding-left: 20px;
}

.on-time {
  font-size: 10px;
}

.delivery-label {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
}

.extract-map {
  width: 100%;
  display: flex;
  justify-content: space-between;
  .map-show {
    cursor: pointer;
  }
}

::v-deep  .el-form-item--small .el-form-item__label {
  display: flex;
  justify-content: flex-end;
}

.tip-box {
  .content {
    line-height: 25px;
    .color-red {
      color: red;
    }
  }
}
</style>
